package com.cloudcc.mobile.view.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.ImageGridAdapter;
import com.cloudcc.mobile.adapter.ImageGridAdapter.OnAddImageListener;
import com.cloudcc.mobile.adapter.ImageGridAdapter.OnShowImageListener;
import com.cloudcc.mobile.adapter.ImageGridAdapter.OndeleteListener;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.EventTaskEntity;
import com.cloudcc.mobile.entity.map.MapLocation;
import com.cloudcc.mobile.event.EventTaskEventList.SendEventEvent;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.EventOrTaskPresenter;
import com.cloudcc.mobile.util.ImageUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.customer.CustomerActivity;
import com.cloudcc.mobile.weight.GridViewForListView;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.litesuits.android.log.Log;

/**
 * 签到编辑类
 *
 * @author Administrator
 */
public class EditorActivity extends BaseActivity implements IEventLife {
    private String mEns = RunTimeManager.getInstance().getlanguage();

    @Bind(R.id.neirong)
    EditText etContent;

    @Bind(R.id.fromname)
    TextView fromname;
    @Bind(R.id.lefttext)
    TextView tvAddress;// 位置
    @Bind(R.id.righttxt)
    TextView tvSubject;// 主题

    @Bind(R.id.addimage)
    ImageView addimage;
    @Bind(R.id.takephoto)
    ImageView takephoto;

    @Bind(R.id.leftr)
    RelativeLayout left;
    @Bind(R.id.rightr)
    RelativeLayout right;

    @Bind(R.id.add_pic_grid)
    GridViewForListView addpic;

    public MapLocation currentLoc = new MapLocation();// 位置

    private List<AddImageInfo> mAddImageArray = new ArrayList<AddImageInfo>();// 将要上传的图片的结合
    private ImageGridAdapter imageGridAdapter;
    private int TO_PIC_IMAGE = 1;
    private int TO_PHOTO_IMAGE = 2;
    private String imagename;
    private String eventContent;// 签到内容
    private String qidaoName;
    private String eventWhoId;// 潜在客户用的who 潜在客户对象
    private String eventSubject;// 主题 类型
    private String from;
    private String key;
    private String reuevantType = "";
    boolean hasAddress = true;
    EventOrTaskPresenter mPresenter = new EventOrTaskPresenter();

    private String startTime, endTime;

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        register();
        setupView();
        fillData();

    }

    // 签到点击照相事件
    @OnClick(R.id.takephoto)
    public void onClickTakePhoto() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory() + "/"
                    + "CloudCC/photo/");
            if (!dir.exists())
                dir.mkdirs();
            imagename = Tools.getTimeName(System.currentTimeMillis());
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);

            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, TO_PHOTO_IMAGE);

        } else {
            Tools.showInfo(EditorActivity.this, "请插入SD卡");
        }

    }

    @OnClick(R.id.addimage)
    public void onClickChoicePhoto() {
        Intent intent = new Intent(mContext, SelectPhotoActivity.class);
        startActivityForResult(intent, TO_PIC_IMAGE);

    }

    @OnClick(R.id.quxiao)
    public void onClickBack() {
        if (from.equals("calllog")){
            Intent intent = new Intent(this,CallLogActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
            finish();
    }

    @OnClick(R.id.leftr)
    public void onClickAddress() {
        if ("en".equals(mEns)) {

        } else {

        }
        if ("en".equals(mEns)) {
            tvAddress.setText(!hasAddress ? currentLoc.getAddress() : "on position");
        } else {
            tvAddress.setText(!hasAddress ? currentLoc.getAddress() : "插入位置");
        }

        hasAddress = !hasAddress;

    }

    @OnClick(R.id.sendd)
    public void onClickSend() {

        if ("en".equals(mEns)) {
            showWainting("Check out, please wait...");
        } else {
            showWainting("正在签到,请稍等...");
        }

        AppContext.isSelectedNum = 0;
        eventContent = StringUtils.isBlank(etContent.getText().toString()) ? etContent
                .getHint().toString() : etContent.getText().toString();

        EventTaskEntity event = new EventTaskEntity();
        // 所有人
        event.setBelongtoid(UserManager.getManager().getUser().userId);
        event.setBelongtoidccname(UserManager.getManager().getUser().userName);
        event.setOwnerid(UserManager.getManager().getUser().userId);

        // 设置task 还是event
        if (TextUtils.equals(key, String.valueOf(2))) {// 2代表task
            event.setIstask(String.valueOf(1));
            event.setExpiredate(Tools.getYMDTime(System.currentTimeMillis()));
        } else {
            event.setIstask(String.valueOf(0));
            String begintime = Tools.getTime(System.currentTimeMillis());
            // .getTime(System.currentTimeMillis() - 600000);
            String endtime2 = Tools.getTime(System.currentTimeMillis());
            // String endtime = Tools.getTime(System.currentTimeMillis() -
            // 500000);
            event.setBegintime(begintime);
            event.setEndtime(endtime2);
        }
        // 区分 联系人 潜在客户 跟 客户 的不同字段赋值
        if (StringUtils.isNotBlank(eventWhoId)) {
            String eventSubTypeId = StringUtils.substring(eventWhoId, 0, 3);
            if (TextUtils.equals(eventSubTypeId, "003")
                    || TextUtils.equals(eventSubTypeId, "004")) {// 联系人 潜在客户
                event.setWhoid(eventWhoId);
                event.setWhoobj(eventSubTypeId);
            } else {// 客户
                event.setRelateid(eventWhoId);
                event.setRelateobj(eventSubTypeId);
            }
        }
        if (startTime != null && startTime.length() != 0) {
            event.setBegintime(startTime);
            event.setEndtime(endTime);
        }
        // 备注
        event.setRemark(eventContent);
        event.setSubject(qidaoName);
        Log.d("shifoucongzheli", qidaoName + "feirenwu");
        event.setIsemailnotification(String.valueOf(true));
        event.setIsremider(String.valueOf(true));
        event.setType(eventSubject);
        event.setName(eventSubject);
        event.setIscompleted(String.valueOf(1));
        event.setStatus("已结束");
        if (hasAddress && null != currentLoc) {
            event.setPosition(currentLoc.getAddress());
        }
        if (!hasAddress) {
            currentLoc = null;
        }
        // Log.d("eventtag",
        // event.getName()+event.getSubject()+event.getRemark()+event.getWhoid()+event.getWhoobj());
        mPresenter
                .sendEventAndInsertTimeLine(event, currentLoc, mAddImageArray);

    }

    private void onHasSend() {
        if (key.equals("2") || key.equals("1")) {
            finish();
        } else {
            finish();
            AppManager.getInstance().finishActivity(CustomerActivity.class);
            AppManager.getInstance().finishActivity(MapsActivity.class);
        }
    }

    // 获取控件
    public void setupView() {

        if ("en".equals(mEns)) {
            tvAddress.setText("Is positioning");
        } else {
            tvAddress.setText("正在定位");
        }

        left.setClickable(false);
        tvAddress.setClickable(false);
        qidaoName = getIntent().getStringExtra("CustomerActivity");
        Log.d("shifoucongzheli", qidaoName + "gangjieshou");
        eventWhoId = getIntent().getStringExtra("urlId");
        reuevantType = getIntent().getStringExtra("reuevantType");
        from = getIntent().getStringExtra("from");
        key = getIntent().getStringExtra("key");
        eventSubject = getIntent().getStringExtra("name");
        currentLoc = (MapLocation) getIntent().getSerializableExtra(
                "MapsActivity");

        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");

        if (currentLoc == null) {// 没有传递过位置来 重新定位
            LocationManager.getInstance().registerListener(mListener);
            LocationManager.getInstance().requestLocal();
        }

    }

    // 初始化数据
    private void fillData() {
        imageGridAdapter = new ImageGridAdapter(this, mAddImageArray);
        addpic.setAdapter(imageGridAdapter);
        setAdapterListener();
        if (currentLoc != null) {
            if (currentLoc.getAddress().length() > 14) {
                tvAddress.setText(currentLoc.getAddress().substring(0, 13)
                        + "...");
                left.setClickable(true);
                tvAddress.setClickable(true);
            } else {
                tvAddress.setText(currentLoc.getAddress());
                left.setClickable(true);
                tvAddress.setClickable(true);
            }
        }
        if (from.equals("map")) {
            tvSubject.setText(eventSubject);
            Log.d("tvSubject", eventSubject);

            if ("en".equals(mEns)) {
                eventSubject = "Sign in to visit";
                fromname.setText("activity:" + reuevantType);
                etContent.setHint("activity:" + reuevantType);
            } else {
                eventSubject = "签到拜访";
                fromname.setText("活动:" + reuevantType);
                etContent.setHint("活动:" + reuevantType);
            }

        } else {
            // from=web

            if ("en".equals(mEns)) {
                fromname.setText("activity:" + reuevantType);
                etContent.setHint("activity:" + reuevantType);
            } else {
                fromname.setText("活动:" + reuevantType);
                etContent.setHint("活动:" + reuevantType);
            }

            if (AppContext.relevantName != null) {
                tvSubject.setText(AppContext.relevantName);
                Log.d("tvSubject", AppContext.relevantName);
            }

            if(from.equals("calllog")){
                fromname.setText(getString(R.string.call_log_avtivity_add_phone));
            }
        }
    }

    // GridView监听
    private void setAdapterListener() {
        addpic.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                imageGridAdapter.setDeleteModel(false);
                return true;
            }
        });
        imageGridAdapter.setOnAddImageListener(new OnAddImageListener() {
            @Override
            public void add() {
                AppContext.isSelectedNum = mAddImageArray.size();
                Intent intent = new Intent(mContext, SelectPhotoActivity.class);
                startActivityForResult(intent, TO_PIC_IMAGE);
            }
        });
        imageGridAdapter.setOndeleteListener(new OndeleteListener() {
            @Override
            public void delete(int posion) {
                mAddImageArray.remove(posion);
                if (mAddImageArray.size() == 0) {
                    imageGridAdapter.setDeleteModel(false);
                } else {
                    imageGridAdapter.notifyDataSetChanged();
                }

            }
        });
        imageGridAdapter.setOnShowImageListener(new OnShowImageListener() {
            @Override
            public void show(int posion) {
                File file = new File(mAddImageArray.get(posion).getImagePath());
                Intent it = new Intent(Intent.ACTION_VIEW);
                Uri mUri = Uri.parse("file://" + file.getPath());
                it.setDataAndType(mUri, "image/*");
                startActivity(it);
            }
        });

    }

    /**
     * 发送成功
     *
     * @param event
     */
    public void onEventMainThread(SendEventEvent event) {
        dismissWainting();
        if (event.isOk()) {

            if (from.equals("calllog")) {
                if ("en".equals(mEns)) {
                    showToast("Add activity save success!!");
                } else {
                    showToast("添加活动保存成功");
                }
            } else {
                if ("en".equals(mEns)) {
                    showToast("Sign in success!!");
                } else {
                    showToast("签到成功!!");
                }
            }


            RefreshDynamicListEvent refreshDynamicListEvent = new RefreshDynamicListEvent();
            EventEngine.post(refreshDynamicListEvent);
        } else {
            if (from.equals("calllog")) {
                if ("en".equals(mEns)) {
                    showToast("Add activity save failed!!" + event.getMessage());
                } else {
                    showToast("添加活动保存失败" + event.getMessage());
                }
            } else {
                if ("en".equals(mEns)) {
                    showToast("Check in failed!!" + event.getMessage());
                } else {
                    showToast("签到失败!!" + event.getMessage());
                }
            }

        }
        onHasSend();
    }

    private ImageView mSourImage;
    private ImageView mWartermarkImage;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == TO_PIC_IMAGE) {
            new Thread() {
                public void run() {
                    setPhotos();
                }

                ;
            }.start();
        } else if (requestCode == TO_PHOTO_IMAGE && resultCode == RESULT_OK) {
            if (mAddImageArray.size() + 1 > 9) {

                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "Add up to 9 images");
                } else {
                    Tools.showInfo(mContext, "最多添加9张图片");
                }

            } else {
                // imagename = Tools.getTimeName(System.currentTimeMillis());
                File f = new File(Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo/" + imagename);
                try {
                    Uri u = Uri.parse(MediaStore.Images.Media
                            .insertImage(getContentResolver(),
                                    f.getAbsolutePath(), null, null));
                    String imageurl = getAbsoluteImagePath(u);

                    // 将图片加上水印
                    Bitmap sourBitmap = ImageUtil.getDiskBitmap(imageurl);
                    String name = "By"
                            + UserManager.getManager().getUser().userName;
                    String time = Tools.getTime2(System.currentTimeMillis());
                    String address = currentLoc.getAddress();
                    // Bitmap fugai =
                    // BitmapFactory.decodeResource(getResources(), R.id.a);
                    String address1 = null;
                    String address2 = null;
                    Bitmap textBitmap = ImageUtil.drawTextToLeftBottom(this,
                            sourBitmap, name, 100, Color.WHITE, 20, 130);
                    textBitmap = ImageUtil.drawTextToLeftBottom(this,
                            textBitmap, time, 100, Color.WHITE, 20, 100);
                    textBitmap = ImageUtil.drawTextToLeftBottom(this,
                            textBitmap, "", 40, Color.WHITE, 20, 85);
                    if (address.length() > 20) {
                        address1 = address.substring(0, 20);
                        address2 = address.substring(11, address.length());
                        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                                textBitmap, address1, 100, Color.WHITE, 20, 70);
                        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                                textBitmap, address2, 100, Color.WHITE, 20, 40);

                    } else {
                        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                                textBitmap, address, 100, Color.WHITE, 20, 30);
                    }

                    // 存储图片
                    savePhotoToSDCard(Environment.getExternalStorageDirectory()
                                    + "/" + "CloudCC" + "/photo", imagename + ".jpg",
                            textBitmap);
                    imageurl = Environment.getExternalStorageDirectory() + "/"
                            + "CloudCC" + "/photo/" + imagename + ".jpg";
                    AddImageInfo imageInfo = new AddImageInfo();
                    imageInfo.setImagePath(imageurl);
                    mAddImageArray.add(imageInfo);
                    imageGridAdapter = new ImageGridAdapter(this,
                            mAddImageArray);
                    addpic.setAdapter(imageGridAdapter);
                    addpic.setVisibility(View.VISIBLE);
                    setAdapterListener();
                } catch (FileNotFoundException e) {
                    Tools.handle(e);
                }
            }
        }
    }

    public void savePhotoToSDCard(String path, String photoname, Bitmap pBitmap) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdirs();
                File photoFile = new File(path, photoname);
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(photoFile);
                    if (pBitmap != null) {
                        if (pBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                fileOutputStream)) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }

    Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if ("en".equals(mEns)) {
                        Tools.showInfo(mContext, "Add up to 9 images");
                    } else {
                        Tools.showInfo(mContext, "最多添加9张图片");
                    }
                    break;
                case 2:
                    imageGridAdapter = new ImageGridAdapter(EditorActivity.this,
                            mAddImageArray);
                    addpic.setAdapter(imageGridAdapter);
                    addpic.setVisibility(View.VISIBLE);
                    setAdapterListener();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void setPhotos() {
        ArrayList<String> picPaths = AppContext.selectPhotos;
        if (mAddImageArray.size() + picPaths.size() > 9) {
            handler2.sendEmptyMessage(1);
            picPaths.clear();
            return;
        } else {
            for (int i = 0; i < picPaths.size(); i++) {
                AddImageInfo imageInfo = new AddImageInfo();
                // Bitmap bitmap=ImageUtils.getimage(picPaths.get(i));
                // String
                // path=ImageUtils.SaveImage(System.currentTimeMillis()+".jpg",
                // ImageUtils.Bitmap2Bytes(bitmap));
                // imageInfo.setBitmap(bitmap);
                imageInfo.setImagePath(picPaths.get(i));
                mAddImageArray.add(imageInfo);
            }
            if (mAddImageArray.size() > 9) {
                handler2.sendEmptyMessage(1);
                picPaths.clear();
                return;
            } else {
                handler2.sendEmptyMessage(2);
            }
            picPaths.clear();
        }
    }

    @Override
    protected void onDestroy() {
        unRegister();
        LocationManager.getInstance().unregisterlistener(mListener);
        try {
            AppContext.isSelectedNum = 0;
        } catch (Exception e) {
            Tools.handle(e);
        }
        super.onDestroy();
    }

    public String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)

        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                LocationManager.getInstance().stopRequestLocal();
                currentLoc = new MapLocation();
                currentLoc.setAddress(LocationManager.getDetailAddr(location,
                        false));
                currentLoc.setLatitude(location.getLatitude());
                currentLoc.setLongitude(location.getLongitude());
                currentLoc.setName(LocationManager.getDetailAddr(location,
                        false));
                tvAddress.setText(currentLoc.getAddress());
                left.setClickable(true);
                tvAddress.setClickable(true);
            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Positioning failed, please try again! Error code:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.map_editor;
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }
}
